package com.yonder.gocommand.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.stereotype.Repository;

import com.yonder.gocommand.dao.IUserDAO;
import com.yonder.gocommand.entity.User;

@Repository("UserDao")
public class UserDAOImpl extends HibernateTransactionManager implements IUserDAO {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(IUserDAO.class);
	
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public void saveOrUpdate(User u) {
		LOGGER.info("saveOrUpdate");
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(u);
	}

	@Override
	public User existUser(String u) {
		LOGGER.info("existUser");
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from User u where u.username = :username");
		query.setParameter("username", u);
		List<?> users = query.list();
		if (users.isEmpty())
			return null;
		else
			return (User) users.get(0);
	}
}
